package com.wux.labs.spring.springbucks.configuration

import org.springframework.boot.context.properties.ConfigurationProperties
import org.springframework.cache.CacheManager
import org.springframework.cache.annotation.EnableCaching
import org.springframework.context.annotation.Bean
import org.springframework.context.annotation.Configuration
import org.springframework.data.redis.cache.RedisCacheConfiguration
import org.springframework.data.redis.cache.RedisCacheManager
import org.springframework.data.redis.connection.RedisConnectionFactory
import org.springframework.data.redis.serializer.GenericJackson2JsonRedisSerializer
import org.springframework.data.redis.serializer.RedisSerializationContext
import org.springframework.data.redis.serializer.StringRedisSerializer
import java.time.Duration

@Configuration
@ConfigurationProperties(prefix = "redis")
@EnableCaching
class RedisConfiguration {

    var ttl: Map<String, Long> = HashMap()

    /**
     * 缓存管理器
     *
     * @param redisConnectionFactory
     * @return
     */
    @Bean
    fun cacheManager(redisConnectionFactory: RedisConnectionFactory): CacheManager? {
        var defaultCacheConfiguration = RedisCacheConfiguration.defaultCacheConfig()

        // 设置缓存管理器管理的缓存的默认过期时间
        defaultCacheConfiguration = defaultCacheConfiguration.entryTtl(Duration.ofSeconds(30L))
            .serializeKeysWith(RedisSerializationContext.SerializationPair.fromSerializer(StringRedisSerializer.UTF_8))
            .serializeValuesWith(
                RedisSerializationContext.SerializationPair.fromSerializer(
                    GenericJackson2JsonRedisSerializer()
                )
            )
            .disableCachingNullValues()

        // 对每个缓存空间应用不同的配置
        val configMap: MutableMap<String, RedisCacheConfiguration> = HashMap()
        ttl.entries.forEach {
            configMap[it.key] = defaultCacheConfiguration.entryTtl(Duration.ofSeconds(it.value))
        }

        return RedisCacheManager.builder(redisConnectionFactory)
            .cacheDefaults(defaultCacheConfiguration)
            .withInitialCacheConfigurations(configMap)
            .build()
    }
}